package com.zhika.zishi.customview;

import android.content.Context;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.ListView;

import com.zhika.zishi.R;

public class LoadListView extends ListView implements OnScrollListener {

    private View footer;

    private int totalItemCount;
    private int lastVisibleItem;
    private boolean isLoading;
    private ILoadListener iLoadListener;

    public LoadListView(Context context) {
        super(context);

        initView(context);
    }

    public LoadListView(Context context, AttributeSet attrs) {
        super(context, attrs);

        initView(context);
    }

    public LoadListView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);

        initView(context);
    }

    /**
     * 初始化listView
     *
     * @param context
     */
    private void initView(Context context) {
        LayoutInflater inflater = LayoutInflater.from(context);
        footer = inflater.inflate(R.layout.footer_layout, null);
        footer.findViewById(R.id.load_layout).setVisibility(View.GONE);
        this.addFooterView(footer);
        this.setOnScrollListener(this);
    }

    @Override
    public void onScroll(AbsListView view, int firstVisibleItem,
                         int visibleItemCount, int totalItemCount) {

        this.lastVisibleItem = firstVisibleItem + visibleItemCount;
        this.totalItemCount = totalItemCount;
    }

    @Override
    public void onScrollStateChanged(AbsListView view, int scrollState) {

        if (totalItemCount == lastVisibleItem
                && scrollState == SCROLL_STATE_IDLE) {
            if (!isLoading) {
                isLoading = true;
                footer.findViewById(R.id.load_layout).setVisibility(
                        View.VISIBLE);
                // 加载更多事件
                iLoadListener.onLoad();
            }
        }
    }

    /**
     * 加载更多完成
     */
    public void loadComplete() {
        isLoading = false;
        footer.findViewById(R.id.load_layout).setVisibility(
                View.GONE);
    }

    /**
     * activity中调用此方法初始化接口
     * @param iLoadListener
     */
    public void setInterface(ILoadListener iLoadListener) {
        this.iLoadListener = iLoadListener;
    }

    /**
     * 加载更多接口
     */
    public interface ILoadListener {
        public void onLoad();
    }
}
